import json
import os.path
import time

import requests
import pandas as pd

# 参数配置
startDate = 20220301
endDate = 20220531

users = [{
    "username": "xxx",
    "password": "xxx"
}]


def get_flow_water(cookie, username):
    flow_water_list = []
    headers = {"cookie": cookie}
    res = requests.get(f"http://localhost:8082/card/flowWater?startDate={startDate}&endDate={endDate}",
                       headers=headers).json()
    time.sleep(3)

    if res["code"] != 200:
        print(f"[ERROR] student ID: {username}, pageNum: {1}")
        return
    pageNum = res["data"]["pageNum"]
    for item in res["data"]["list"]:
        flow_water_list.append(item)

    print(f"[OK] student ID: {username}, index: {1} pageNum: {pageNum} data: {res['data']['list']}")

    for index in range(2, pageNum + 1):
        res = requests.get(f"http://localhost:8082/card/flowWater?startDate=20220501&endDate=20220531&pageNum={index}",
                           headers=headers).json()
        time.sleep(3)

        if res["code"] != 200:
            print(f"[ERROR] student ID: {username}, index: {index} pageNum: {pageNum}")
            return

        for item in res["data"]["list"]:
            flow_water_list.append(item)
        print(f"[OK] student ID: {username}, index: {index} pageNum: {pageNum} data: {res['data']['list']}")

    data = pd.read_json(json.dumps(flow_water_list))
    data.to_csv(f"./data/flow-water-{username}-{startDate}-{endDate}.csv", encoding="utf_8_sig", index=0)


def main():
    for user in users:
        res = requests.get(
            f"http://localhost:8082/login?username={user['username']}&password={user['password']}").json()
        time.sleep(3)
        if res['code'] == 200:
            print("[OK] login successful")
            get_flow_water(res["data"]["cookie"], user['username'])


if __name__ == "__main__":
    if not os.path.exists("./data"):
        os.mkdir("./data")
    main()
